package com.itheima.controller;

import com.itheima.admin.pojo.Employee;
import com.itheima.common.R;
import com.itheima.common.TokenHolder;
import com.itheima.service.EmployeeService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @Author longbosheng
 * @Date 2022/6/11 16:39
 * @PackageName:com.itheima.controller
 * @ClassName: EmployeeController
 * @Description: TODO
 * @Version 1.0
 */
@Log4j2
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Resource
    private EmployeeService employeeService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 员工登录
     *
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody Employee employee) {
        //加密密码
        String newPwd = DigestUtils.md5DigestAsHex(employee.getPassword().getBytes());
        employee.setPassword(newPwd);
        return employeeService.login(employee);
    }

    /**
     * 员工登出
     *
     * @return
     */
    @PostMapping("/logout")
    public R logout(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token == null) {
            return R.success("返回到页面");
        }
        Boolean delete = redisTemplate.delete(token);
        if (delete) {
            return R.success("退出成功");
        }
        return R.error("退出失败");

    }

    /**
     * 添加员工
     *
     * @param employee
     * @return
     */
    @PostMapping
    public R insertEmployee(@RequestBody Employee employee) {
//        获取token中的id
        String id = TokenHolder.getCurrentId();
//        将操作者的id放入实体类对象中
        employee.setCreateUser(id);
        return employeeService.insertEmployee(employee);
    }

    /**
     * 分页查询员工
     *
     * @return
     */
    @GetMapping("/page")
    public R selectEmployee(String name, int page, Integer pageSize) {
        log.info("name:" + name + " page:" + page + " pageSize:" + pageSize);
        return employeeService.showEmployee(name, page, pageSize);
    }

    /**
     * 按照id查询员工信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R selectEmployeeById(@PathVariable Integer id) {
        return employeeService.selectEmployeeById(id);
    }

    /**
     * 启用/禁用/修改员工信息
     *
     * @param employee
     * @return
     */
    @PutMapping
    public R UpdateEmployee(@RequestBody Employee employee) {
        //        获取token中的id
        String id = TokenHolder.getCurrentId();

        log.info("employee:" + employee);
        log.info("员工表实体类信息：" + employee);
        //        将操作者的id放入实体类对象中
        employee.setUpdateUser(id);
        return employeeService.updateEmployee(employee);
    }
}
